package com.pactera.madp.cp.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.pactera.madp.admin.api.vo.SysFileVo;
import com.pactera.madp.common.core.constant.CommonConstants;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.common.config.FileUploadConfig;
import com.pactera.madp.cp.service.FileUploadService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;

/**
 * FileUploadServiceImpl
 *
 * @author jun
 * @version 1.0
 * 2021/7/8 14:03
 **/
@Service
@Slf4j
@AllArgsConstructor
public class FileUploadServiceImpl implements FileUploadService {

    private final FileUploadConfig fileUploadConfig;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public R uploadFile(MultipartFile file) {
        log.info("upload file start...");
        SysFileVo vo = null;

        log.info("原始文件名为："+file.getOriginalFilename());
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
        log.info("文件名为："+fileName);
        String url = "";

        Long fileSize = file.getSize();
        log.info("文件大小为："+file);
        url = String.format(fileUploadConfig.getAccessPath() + "/%s", fileName);
        log.info("文件url为: "+url);
        String realPath = fileUploadConfig.getRealPath();
        log.info("文件真实上传路径为："+realPath);

        try{
            File dest = new File(realPath + "/" + fileName);
            file.transferTo(dest);
        }catch (Exception e) {
            log.error("上传失败", e);
            return R.failed(e.getLocalizedMessage());
        }
        log.info("store file finish...");
        //设置返回
        vo = handleFile(file, fileName, url, fileSize);
        return R.ok(vo);
    }


    /**
     * 文件响应信息处理
     * @param file
     * @param fileName
     * @param url
     * @return
     */
    private SysFileVo handleFile(MultipartFile file, String fileName, String url, Long fileSize){
        SysFileVo vo = new SysFileVo();
        //原文件名
        String original = file.getOriginalFilename();
        vo.setBucketName(CommonConstants.BUCKET_NAME);
        vo.setFileName(fileName);
        vo.setOriginal(original);
        vo.setFileSize(fileSize);
        vo.setType(FileUtil.extName(original));
        vo.setUrl(url);

        return vo;
    }
}
